﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Runda.EShop.Common.Utility;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using System.Configuration.Install;

namespace Runda.EShop.Service.WMS
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            string serviceName = "Runda WMS Interface Service";

            string resultMsg = string.Empty;
            List<string> argList = new List<string>(args);

            if (argList.Contains("/?"))
            {
                Console.WriteLine(Path.GetFileNameWithoutExtension(Application.ExecutablePath) + " [winapp] [/i] [/u]");
            }
            //支持自行安装服务
            else if (argList.Contains("/i") == true)
            {
                resultMsg = SelfInstaller.InstallMe();
                if (string.IsNullOrEmpty(resultMsg) == false)
                    MessageBox.Show("由于下列原因服务" + serviceName + "安装失败：\r\n" + resultMsg, serviceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("成功安装：" + serviceName, serviceName);
            }
            else if (argList.Contains("/u") == true)
            {
                resultMsg = SelfInstaller.UninstallMe();
                if (string.IsNullOrEmpty(resultMsg) == false)
                    MessageBox.Show("由于下列原因服务" + serviceName + "卸载失败：\r\n" + resultMsg, serviceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("成功卸载：" + serviceName, serviceName);
            }
            else
            {
                if (argList.Contains("winapp") == true) //应用程序模式
                {
                    InnerService service = new InnerService(1);
                    service.Start();
                    //new Thread(Test1).Start();

                    Console.WriteLine("服务已启动...");
                  
                    while (!Console.ReadLine().Equals("exit", StringComparison.OrdinalIgnoreCase)) { }
                    //service.Stop();
                }
                else //win service模式
                {
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[] { new WMSService() };
                    ServiceBase.Run(ServicesToRun);
                }
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            LogHelper.Write("服务安装失败：" + ex.Message);
        }
    }

    /// <summary>
    /// 使服务可以自我安装
    /// </summary>
    public static class SelfInstaller
    {
        private static readonly string _exePath = Assembly.GetExecutingAssembly().Location;

        public static string InstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(new string[] { _exePath });
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return string.Empty;
        }

        public static string UninstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(new string[] { "/u", _exePath });
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return string.Empty;
        }
    }
}
